package gao.xioalei.stream;

import gao.xioalei.dao.UserOnlineDao;
import gao.xioalei.entity.Message;
import gao.xioalei.util.ServiceName;
import gao.xioalei.util.WebSocketUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Optional;

@EnableBinding(StreamClient.class)//@EnableBinding和@ServerEndpoint放在一起的话@ServerEndpoint会报无法注册bean的错误
public class Binder {
    @Autowired
    private StreamClient streamClient;

    @Autowired
    private RestTemplate restTemplate;

    public void sendMessage(Message message, String routingKey) {
        streamClient.output().send(MessageBuilder.withPayload(message).setHeader("routingKey", routingKey).build());
    }

    //但接收到消息队列的消息时
    @StreamListener(value = StreamClient.INPUT)
    public void receiveMessage(Message message) {
        //如果用户在这个服务的session还有效的话
        System.out.println(message.getOnLineId());
        Optional.ofNullable(WebSocketUtil.USERS_ONLINE.get(message.getOnLineId())).ifPresent(session -> {
            if(message.getType()==0){//只有即时聊天消息才要拿发送人昵称
                String senderName = restTemplate.getForObject(ServiceName.AUTH_SERVICE.getServiceName().concat("/user/realName/").concat(message.getSender()), String.class);
                message.setSenderName(senderName);
            }
            WebSocketUtil.sendMessage(session, message);//向目标用户发送消息
        });
    }
}
